Skip to content

Conversation

woodymelling
Copy link

I’ve been exploring the concept of Conversions recently and discovered they’re incredibly powerful. They seem to be a bit more broad than the ParserPrinters provided by swift-parsing.

A ParserPrinter transforms nebulous data into structured data while consuming part of the input, and can also print the structured data back into a the nebulous form. In contrast, a Conversion focuses solely on the ability to convert between two types, potentially throwing errors, without any notion of input consumption or output printing. This aligns with the “parse, don’t validate” philosophy, making Conversions useful when dealing with data that isn’t strictly string-based—allowing you to transform it directly into Swift types without worrying about parsing steps.

I’m submitting this PR as a result of these explorations and am curious if this approach is of interest. I believe it could be broadly applicable, especially when defining persistence strategies.

This PR includes:

  • Extracting Conversions into their own module, emphasizing their utility even outside of parsing scenarios.
  • Introducing a ResultBuilder for constructing complex conversions from simpler ones. For example:
struct PostConversion: Conversion {
    typealias Input = [FileContent<Data>]
    typealias Output = [Blog.Post]

    var body: some Conversion<Input, Output> {
        Conversions.MapValues {
            FileContentConversion(.json(Blog.PostBody.self))

            AnyConversion {
                Blog.Post(
                    slug: $0.fileName,
                    body: $0.content
                )
            } unapply: {
                FileContent(
                    fileName: $0.slug,
                    data: $0.body
                )
            }
        }
    }
}
  • Providing a set of useful conversions, such as inversion of existing conversions, value mapping, and dictionary transformations.

@woodymelling woodymelling marked this pull request as draft December 6, 2024 17:37
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant